package edu.ucdavis.gwt.gis.client.export;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;

import edu.ucdavis.gwt.gis.client.extras.CloseButton;

public class ExportLegendPopup extends PopupPanel {
	
	private static ExportLegendPopupUiBinder uiBinder = GWT.create(ExportLegendPopupUiBinder.class);
	interface ExportLegendPopupUiBinder extends UiBinder<Widget, ExportLegendPopup> {}
	
	public static final ExportLegendPopup INSTANCE = new ExportLegendPopup();

	@UiField CloseButton closeButton;
	@UiField ScrollPanel legendPanel;
	@UiField Image legend;
	
	protected ExportLegendPopup() {
		setWidget(uiBinder.createAndBindUi(this));
		setStyleName("ExportLegendPopup");
		setGlassStyleName("ExportLegendPopup-glass");
		setGlassEnabled(true);
		setAutoHideEnabled(false);
		
		//addAttachHandler(attachHandler);
		closeButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				hide();
			}
		});
		
		legend.addLoadHandler(new LoadHandler(){
			@Override
			public void onLoad(LoadEvent event) {
				int h = legend.getOffsetHeight()+10;
				if( h > Window.getClientHeight()-100 ) h = Window.getClientHeight()-100;
				legendPanel.setSize((legend.getOffsetWidth()+20)+"px", h+"px");
				center();
			}
		});
		
	}
	
	public void showLegend(String base64Data) {
		legend.setUrl(base64Data);
		center();
	}
	
	private Handler attachHandler = new Handler() {
		@Override
		public void onAttachOrDetach(AttachEvent event) {
			if( event.isAttached() ) {
				int h = legend.getOffsetHeight();
				if( h > Window.getClientHeight()-100 ) h = Window.getClientHeight()-100;
				legendPanel.setSize((legend.getOffsetWidth()+20)+"px", h+"px");
				center();
			}
		}
	};


}
